const mongoose = require('mongoose');

// 定义User Schema
const userSchema = new mongoose.Schema({
  _id: {
    type: Number,
    required: true
  },
  name: {
    type: String,
    required: [true, '姓名是必需的'],
    trim: true
  },
  email: {
    type: String,
    required: [true, '邮箱是必需的'],
    unique: true,
    trim: true,
    validate: {
      validator: function(v) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
      },
      message: props => `${props.value} 不是有效的邮箱地址!`
    }
  }
});

// 静态验证方法
userSchema.statics.validateUser = function (userData) {
  const errors = [];
  
  if (!userData.name || userData.name.trim() === '') {
    errors.push('姓名是必需的');
  }
  
  if (!userData.email || userData.email.trim() === '') {
    errors.push('邮箱是必需的');
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userData.email)) {
    errors.push('邮箱格式不正确');
  }
  
  return {
    valid: errors.length === 0,
    errors
  };
};

// 创建User模型
const User = mongoose.model('User', userSchema);

// 初始用户数据
const users = [
  { id: 1, name: '张三', email: 'zhangsan@example.com' },
  { id: 2, name: '李四', email: 'lisi@example.com' },
  { id: 3, name: '王五', email: 'wangwu@example.com' }
];

module.exports = {
  User,
  users
};